<template>
  <a-card :bordered="false" :loading="loading">
    <div class="w-full">
      <a-form
        class="m-t-10"
        :model="dynamicValidateForm"
        :label-col="{ span: 4 }"
        :wrapper-col="{ span: 20 }"
        @finish="onFinish"
        @finish-failed="onFinishFailed"
      >
        <a-row :gutter="24">
          <a-col :span="12">
            <a-form-item
              label="美食名称"
              name="name"
              :rules="{ required: true, message: '请输入美食名称' }"
            >
              <a-input v-model:value="dynamicValidateForm.name" />
            </a-form-item>
          </a-col>
          <a-col :span="12">
            <a-form-item
              label="封面"
              name="cover"
              :rules="{ required: true, message: '请添加封面' }"
            >
              <upload-image
                :image-str="dynamicValidateForm.cover"
                :component-props="{ maxCount: 1 }"
                upload="上传"
                :max-file-size-mb="4"
                @on-change-upload="(value) => (dynamicValidateForm.cover = value)"
              />
              <span class="text-hex-999">支持拓展名：.jpg.jpeg.png</span>
            </a-form-item>
          </a-col>
          <a-col :span="24" :pull="2">
            <a-form-item label="轮播图片" name="images">
              <upload-image
                :image-str="dynamicValidateForm.images"
                :component-props="{ maxCount: 5 }"
                upload="上传"
                :max-file-size-mb="4"
                @on-change-upload="(value) => (dynamicValidateForm.images = value)"
              />
              <span class="text-hex-999">支持拓展名：.jpg.jpeg.png</span>
            </a-form-item>
          </a-col>
          <a-col :span="12">
            <!--            <div class="inline-flex items-center whitespace-nowrap">-->
            <a-form-item
              label="分类"
              name="categoryId"
              :rules="{ required: true, message: '请选择分类' }"
            >
              <a-select
                v-model:value="dynamicValidateForm.categoryId"
                class="min-w-150px"
                allow-clear
                :options="typeList"
                placeholder="请选择分类"
              ></a-select>
            </a-form-item>
            <!--            </div>-->
          </a-col>
          <a-col :span="12">
            <a-form-item label="排序" name="sort">
              <a-input v-model:value="dynamicValidateForm.sort" />
            </a-form-item>
          </a-col>
          <a-col :span="24" :pull="2">
            <a-form-item label="推荐餐厅" name="restaurantList">
              <a-space
                v-for="(restaurant, index) in dynamicValidateForm.restaurantList"
                :key="restaurant.id"
                style="display: flex; margin-bottom: 8px"
                align="baseline"
              >
                <a-form-item
                  :name="['restaurantList', index, 'name']"
                  :rules="{
                    required: true,
                    message: '请填写餐厅名',
                  }"
                >
                  <a-input
                    v-model:value="restaurant.name"
                    placeholder="餐厅名"
                    style="width: 300px"
                  />
                </a-form-item>
                <a-form-item
                  :name="['restaurantList', index, 'address']"
                  class="flex-1 m-r-4"
                  :rules="{
                    required: true,
                    message: '请填写餐厅地址',
                  }"
                >
                  <a-input
                    ref="addressInput"
                    v-model:value="restaurant.address"
                    class="address_input"
                    placeholder="请选择餐厅地址"
                    style="width: 500px"
                    @click="mapModalVisible = true"
                  />
                </a-form-item>
                <map-modal
                  :visible="mapModalVisible"
                  :selected-location="restaurant.address"
                  :center="[dynamicValidateForm.lng, dynamicValidateForm.lat]"
                  @click="mapModalVisible = true"
                  @ok="onOk(index, $event)"
                  @cancel="onCancel"
                />
                <MinusCircleOutlined @click="removeRestaurant(restaurant)" />
              </a-space>
              <a-form-item>
                <a-button v-if="!hasRestaurant" type="dashed" block @click="addRestaurant">
                  <PlusOutlined />
                  添加推荐餐厅
                </a-button>
              </a-form-item>
            </a-form-item>
          </a-col>
          <a-col :span="24" :pull="1">
            <a-form-item
              label="介绍"
              name="introduce"
              :label-col="{ span: 3 }"
              :wrapper-col="{ span: 21 }"
              :rules="{ required: true, message: '请输入介绍' }"
            >
              <tinymce-editor
                v-model:value="dynamicValidateForm.introduce"
                placeholder="详细介绍"
              ></tinymce-editor>
            </a-form-item>
          </a-col>
        </a-row>
        <!--          </a-row>-->
        <a-form-item :wrapper-col="{ span: 24 }">
          <div class="text-center">
            <a-button class="mr-50px" type="primary" html-type="submit">发布</a-button>
            <a-button @click="closeTab">返回</a-button>
          </div>
        </a-form-item>
      </a-form>
    </div>
  </a-card>
</template>

<script setup lang="tsx">
  import { reactive } from 'vue';
  import { MinusCircleOutlined, PlusOutlined } from '@ant-design/icons-vue';
  import { message } from 'ant-design-vue';
  import DynamicForm from '@/components/dynamicForm/index.vue';
  import useRequestDetail from '@/hooks/useRequestDetail';
  import { foodApi, createFood, updateFood } from '@/api/food';
  import { useTabsViewStore } from '@/store/modules/tabsView';
  import { ComponentsTypeEnum } from '@/enums/componentsEnum';
  import { categoryJsonByType } from '@/api/category';
  import { categoryTypeEnum } from '@/enums/categoryTypeEnum';
  import { formatToDateTime } from '@/utils/dateUtil';
  import { useUserStore } from '@/store/modules/user';

  defineOptions({
    name: 'foodEdit',
  });

  const userStore = useUserStore();
  const rustic = userStore.getRusticId();

  const format = 'YYYY-MM-DD HH:mm';
  const route = useRoute();
  const router = useRouter();
  const tabsViewStore = useTabsViewStore();
  const mapModalVisible = ref<boolean>(false);
  const hasRestaurant = ref<boolean>(false);
  const typeList = ref<{ id: number; name: string }[]>([]);
  // const restaurantList = ref<
  //   { id: number; name: string; address: string; detailedAddress: string }[]
  // >([]);
  const dynamicValidateForm = reactive<{
    restaurantList: Restaurant[];
    categoryId: number | null;
    cover: string;
    images: string;
    introduce: string;
    name: string;
    rusticId: number | null;
    sort: number | null;
  }>({
    restaurantList: [],
    categoryId: null,
    cover: '',
    images: '',
    introduce: '',
    name: '',
    rusticId: null,
    sort: null,
  });
  const { detailData, loading, getDetail } = useRequestDetail({
    apiKey: foodApi.foodDetail,
    initParams: route?.query,
    isMount: !!Object.values(route?.query).length && !!Object.values(route?.query)[0],
  });

  const getRestaurantList = () => {
    if (route.query?.id) {
      getDetail().then(() => {
        if (detailData.value) {
          // 判断是否为空,不为空
          // console.info('得到的列表===>', detailData.value.restaurantList);
          // restaurantList.value = detailData.value.restaurantList.map(
          //   (item: { name: string; id: number; address: string; detailedAddress: string }) => ({
          //     id: item.id,
          //     name: item.name,
          //     address: item.address,
          //     detailedAddress: item.detailedAddress,
          //   }),
          // );
          if (detailData.value.restaurantList && detailData.value.restaurantList.length > 0) {
            dynamicValidateForm.restaurantList = detailData.value.restaurantList;
            hasRestaurant.value = true;
          }
          dynamicValidateForm.categoryId = detailData.value.categoryId;
          dynamicValidateForm.cover = detailData.value.cover;
          dynamicValidateForm.introduce = detailData.value.introduce;
          dynamicValidateForm.images = detailData.value.images;
          dynamicValidateForm.rusticId = detailData.value.rusticId;
          dynamicValidateForm.name = detailData.value.name;
          dynamicValidateForm.sort = detailData.value.sort;
          // console.info('得到的列表===>', dynamicValidateForm);
        }
      });
    }
  };

  const setRestaurantList = () => {
    // detailData.value.restaurantList = restaurantList;
    detailData.restaurantList = dynamicValidateForm.restaurantList;
    // console.info('转化===>', detailData.restaurantList);
  };

  const submitForm = async (params) => {
    const foodId = route?.query?.id;
    // setRestaurantList();
    const res = foodId
      ? await updateFood({
          ...params,
          id: foodId,
        })
      : await createFood({
          ...params,
          rusticId: rustic,
        });
    if (res) {
      message.success(res?.msg);
      closeTab();
    }
  };

  const onFinish = (values: any) => {
    submitForm(dynamicValidateForm);
  };

  const onFinishFailed = (errorInfo: any) => {
    console.log('Failed:', errorInfo);
  };

  const closeTab = () => {
    tabsViewStore.closeCurrentTab(route);
  };

  const onCancel = () => {
    mapModalVisible.value = false;
  };

  const onOk = (index, data: any) => {
    console.info('modalData ==>,', data);
    // detailData.value = { ...detailData.value, ...data };
    // detailData.value.address = data.location;
    // detailData.value.lng = data.lng;
    // detailData.value.lat = data.lat;
    // 根据 data 中的信息更新对应餐厅的地址
    dynamicValidateForm.restaurantList[index].address = data.location;
  };

  const getCategoryList = async () => {
    const res = await categoryJsonByType({ type: categoryTypeEnum.FOOD });
    if (res) {
      typeList.value = res.data.map((item: { name: string; id: number }) => ({
        label: item.name,
        value: item.id,
      }));
    }
  };

  interface Restaurant {
    name: string;
    address: string;
    detailedAddress: string;
    id: number;
  }

  const removeRestaurant = (item: Restaurant) => {
    const index = dynamicValidateForm.restaurantList.indexOf(item);
    if (index !== -1) {
      dynamicValidateForm.restaurantList.splice(index, 1);
    }
    if (dynamicValidateForm.restaurantList.length === 0) {
      hasRestaurant.value = false; // 没有推荐餐厅了，设置为未添加推荐餐厅
    }
  };

  const addRestaurant = () => {
    if (!hasRestaurant) {
      return; // 已经添加了推荐餐厅，直接返回
    }
    // 添加数据的逻辑
    dynamicValidateForm.restaurantList.push({
      name: '',
      address: '',
      detailedAddress: '',
      id: Date.now(),
    });
    hasRestaurant.value = true; // 设置为已添加推荐餐厅
  };

  // const removeRestaurant = (item: Restaurant) => {
  //   const index = restaurantList.value.indexOf(item);
  //   if (index !== -1) {
  //     restaurantList.value.splice(index, 1);
  //   }
  // };
  //
  // const addRestaurant = () => {
  //   restaurantList.value.push({
  //     name: '',
  //     address: '',
  //     detailedAddress: '',
  //     id: Date.now(),
  //   });
  // };

  onMounted(() => {
    getCategoryList();
    getRestaurantList();
  });
</script>

<style></style>
